package com.example.test.security;

import com.example.test.domain.AccessControlItem;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class CustomSecurityMetadataSource implements SecurityMetadataSource {
    @Getter
    @Setter
    private static Map<AccessControlItem, Collection<ConfigAttribute>> acl;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        for (AccessControlItem item : acl.keySet()) {
            if(item.getRequestMappingInfo().getMatchingCondition(request) != null){
                return acl.get(item);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return acl.values().stream().reduce(new ArrayList<>(), ((configAttributes, roles) -> {
            configAttributes.addAll(roles);
            return configAttributes;
        }));
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
